//
//  RHDeviceLoadVC.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2023/12/7.
//

#import "RHDeviceLoadVC.h"
#import "RHDeviceLoadPieCell.h"
#import "RHDeviceLoadDataCell.h"
#import "DevChartModel.h"
#import "DevChartParamsModel.h"
#import "DeviceChartFieldModel.h"
#import "WSDatePickerView.h"
#import "RHDeviceLoadChartCell.h"
#import "SYChartTool.h"
#import "RHDevEndPointDataModel.h"
#import "RHBatDataModel.h"

@interface RHDeviceLoadVC ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic ,strong) UITableView *tableView;

@property (nonatomic ,strong) DevChartModel *chartModel;

@property (nonatomic ,strong) NSDictionary *loadDic;

@property (nonatomic ,strong) DevChartParamsModel *chartParamsModel;

@property (nonatomic ,strong) RHDevEndPointDataModel *emuModel;

@property (nonatomic ,strong) NSDictionary *batteryDataDic;
@end

@implementation RHDeviceLoadVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    
    [self getData];
}

- (void)setupUI{
    kWeakSelf;
    
    NSDictionary *dict = [SYChartTool readLocalJsonFileWithName:@"DeviceBattery"];
    self.chartParamsModel = [DevChartParamsModel yy_modelWithDictionary:dict];
    
    NSInteger timeInterval = [[NSDate date]timeIntervalSince1970];
    self.chartModel = [[DevChartModel alloc]init];
    self.chartModel.curTime = [NSString stringWithFormat:@"%ld",timeInterval];
   
    self.batteryDataDic = @{
        @"chg_today":@"-- (kWh)",
        @"dchg_today":@"-- (kWh)",
        @"chg_total":@"-- (kWh)",
        @"dchg_total":@"-- (kWh)"
    };
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    _tableView.backgroundColor = CFTabViewBgColor;
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    [_tableView registerClass:[RHDeviceLoadChartCell class] forCellReuseIdentifier:@"RHDeviceLoadChartCell"];
    [_tableView registerClass:[RHDeviceLoadDataCell class] forCellReuseIdentifier:@"PEDeviceLoadCell"];
    [self.view addSubview:_tableView];
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    
    [_tableView addHeaderRefresh:^{
        [weakSelf getData];
        if (weakSelf.updateDevInfoBlock) {
            weakSelf.updateDevInfoBlock();
        }
    }];
}

//获取端点关系
-(void)getDevRelation
{
    [RHDevEndPointDataModel startGetWithCompletionAPIKey:H_getDevRelation argument:@{@"deviceId":self.deviceId} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
            if(resultModel.code == 200){
                if(ValidDict(request.responseJSONObject[@"data"])){
                    NSArray *arr = [NSArray yy_modelArrayWithClass:[RHDevEndPointDataModel class] json:request.responseJSONObject[@"data"][@"data"]];
                    //筛选出EMU
                   
                    [arr enumerateObjectsUsingBlock:^(RHDevEndPointDataModel  *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                            if([obj.type isEqualToString:@"EMU"]){
                                self.emuModel = obj;
                                *stop = YES;
                            }
                    }];
                }
                
                if (self.emuModel) {
                    [self getData];
                }else{
                    [self getDataFromNetwork:[self.chartParamsModel.chartList firstObject]];
                }
            }
            [self.tableView endHeaderRefresh];
        } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
            [self.tableView endHeaderRefresh];
    }];
}


-(void)getData
{

    if(self.emuModel == nil){
        [self getDevRelation];
    }else{
        [self getDataFromNetwork:self.chartParamsModel.chartList.firstObject];
        [self getFormData];
    }
   
}

//曲线
- (void)getDataFromNetwork:(DevChartModel *)chartModel{
    if(self.emuModel==nil){
        [QMUITips showInfo:@"没有EMU模块".rh_localized];
        NSLog(@"------->没有EMU模块");
        return;
    }
    
    NSMutableArray *keys = [NSMutableArray array];
    for (DeviceChartFieldModel *fileld in chartModel.selectArray) {
        [keys addObject:fileld.keyCode];
    }

    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[chartModel.curTime integerValue]];
    NSDate *begin_date = [NSDate dateWithYear:date.year month:date.month day:date.day hour:0 minute:0 second:0];
    NSDate *end_date = [NSDate dateWithYear:date.year month:date.month day:date.day hour:23 minute:59 second:59];
    
    NSString *begin_time = [NSString stringWithFormat:@"%zd",(NSInteger)[begin_date timeIntervalSince1970]*1000];
    NSString *end_time = [NSString stringWithFormat:@"%zd",(NSInteger)[end_date timeIntervalSince1970]*1000];
    
    
    NSDictionary *para = @{@"deviceId":self.deviceId,
                           @"endpointTypeCode":@"EMU",
                           @"keyCodes":keys,
                           @"endpointSn":self.emuModel.sn,
                           @"startTimestamp":begin_time,
                           @"endTimestamp":end_time
    };
    [QMUITips showLoadingInView:self.view];
    [BaseModel startWithCompletionAPIKey:D_getEndpointDataByTime argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
        if(resultModel.code == 200){
            if([request.responseObject[@"data"] isKindOfClass:[NSArray class]]){
                NSArray *dataArr = request.responseObject[@"data"];
  
                chartModel.allDataArray = dataArr;

                [self.tableView reloadData];
            }
        }
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
        
    }];
}

//底部数据(电池数据)
- (void)getFormData{
    
    
    NSDictionary *para = @{
                            @"deviceId":self.deviceId,
                            @"timeZone":[NSTimeZone getCurrentTimeZone]
    };
    
    [BaseModel startGetWithCompletionAPIKey:H_getDeviceBatteryEnergyInfo argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
        if(resultModel.code == 200){
            if([request.responseObject[@"data"] isKindOfClass:[NSDictionary class]]){
                NSDictionary *dic = request.responseObject[@"data"];
          
               //当日充电
                NSString *chg_today = [NSDecimalNumber decimalStringWithDoubleString:dic[@"Emu_BCE_Day"] nullStr:@"--"];
                //当日放电
                NSString *dchg_today = [NSDecimalNumber decimalStringWithDoubleString:dic[@"Emu_BDE_Day"] nullStr:@"--"];
                
                //累计充电
                NSString *chg_total = [NSDecimalNumber decimalStringWithDoubleString:dic[@"Emu_BCE_Ttl"] nullStr:@"--"];
                 //累计放电
             
                NSString *dchg_total = [NSDecimalNumber decimalStringWithDoubleString:dic[@"Emu_BDE_Ttl"] nullStr:@"--"];
                
                self.batteryDataDic = @{
                    @"chg_today":chg_today,
                    @"dchg_today":dchg_today,
                    @"chg_total":chg_total,
                    @"dchg_total":dchg_total
                };
                [self.tableView reloadData];
            }
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
    }];
}


#pragma mark ----------------- Action --------------------
#pragma mark ----- 参数 , 年 , 月 , 日选项 -------------
//工具选择项
- (void)selectTopTool:(NSInteger)index atIndexpath:(NSIndexPath *)indexpath{
    DevChartModel *chartModel = self.chartModel;
    if (index == 0) {//Day
        chartModel.timeType = TimeType_Day;
        NSDate *date = [NSDate date];
        NSTimeInterval interval = [date timeIntervalSince1970];
        chartModel.curTime = [NSString stringWithFormat:@"%d",(int)interval];
        chartModel.params = chartModel.dayParams;
       
    }else if (index == 1) {//Month
        chartModel.timeType = TimeType_Month;
        NSDate *date = [NSDate date];
        NSTimeInterval interval = [date timeIntervalSince1970];
        chartModel.curTime = [NSString stringWithFormat:@"%d",(int)interval];
        chartModel.params = chartModel.monthParams;
//        chartModel.allDataArray = @[];
        [self.tableView reloadData];
        
    }else if (index == 2) {//Year
        chartModel.timeType = TimeType_Year;
        NSDate *date = [NSDate date];
        NSTimeInterval interval = [date timeIntervalSince1970];
        chartModel.curTime = [NSString stringWithFormat:@"%d",(int)interval];
        chartModel.params = chartModel.yearParams;
//        chartModel.allDataArray = @[];
        [self.tableView reloadData];
        
    }else if (index == 4) {//Total
        chartModel.timeType = TimeType_Total;
    }

}
#pragma mark ------ 选择日期 ------
//变更日期
- (void)changeDate:(NSIndexPath *)indexpath{
    DevChartModel *chartModel = self.chartParamsModel.chartList[indexpath.section];
   
    WSDateStyle dataStyle = DateStyleShowYearMonthDay;
    if (chartModel.timeType == TimeType_Day) {
        dataStyle = DateStyleShowYearMonthDay;
    }else if (chartModel.timeType == TimeType_Month){
        dataStyle = DateStyleShowYearMonth;
    }else if (chartModel.timeType == TimeType_Year){
        dataStyle = DateStyleShowYearMonthDay;
    }

    kWeakSelf;
    WSDatePickerView *datePickerV = [[WSDatePickerView alloc] initWithDateStyle:dataStyle CompleteBlock:^(NSDate *selectDate) {
       
        //NSString *currentDate = [selectDate stringWithFormat: dateFormatStr];//年-月-日-时-分
        NSUInteger timeSp = [selectDate timeIntervalSince1970];
        chartModel.curTime = [NSString stringWithFormat:@"%d",(int)timeSp];
        
       
        [weakSelf getDataFromNetwork:weakSelf.chartParamsModel.chartList.firstObject];
       
    }];
    datePickerV.dateLabelColor = FontColor(@"#3ECE80");//年-月 颜色
    datePickerV.datePickerColor = UIColorBlack;//滚轮日期颜色
    datePickerV.doneButtonColor = UIColor.blackColor;//确定按钮的颜色
    if (chartModel.timeType == TimeType_Day) {
        datePickerV.maxLimitDate = [NSDate date];
        datePickerV.minLimitDate = [NSDate dateWithYear:[NSDate date].year-5 month:[NSDate date].month day:[NSDate date].day hour:[NSDate date].hour minute:[NSDate date].minute second:[NSDate date].second];
    }else if (chartModel.timeType == TimeType_Month){

    }else if (chartModel.timeType == TimeType_Year){
        datePickerV.maxLimitDate = [NSDate date];
        datePickerV.minLimitDate = [NSDate dateWithYear:[NSDate date].year-5 month:[NSDate date].month day:[NSDate date].day hour:[NSDate date].hour minute:[NSDate date].minute second:[NSDate date].second];
    }
    [datePickerV show];
}
#pragma mark ------ 后一天 -------
//日期累加
- (void)addTimeAction:(NSIndexPath *)indexpath{
    DevChartModel *chartModel = self.chartParamsModel.chartList[indexpath.section];
  
    if (chartModel.timeType == TimeType_Total) {
        return;
    }
    
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[chartModel.curTime integerValue]];
    NSDate *nextDate;
    if (chartModel.timeType == TimeType_Day) {
        nextDate = [date dateByAddingDays:1];
    }else if (chartModel.timeType == TimeType_Month){
        nextDate = [date dateByAddingMonths:1];
    }else if (chartModel.timeType == TimeType_Year){
        nextDate = [date dateByAddingYears:1];
    }
    NSTimeInterval interval = [nextDate timeIntervalSince1970];
    chartModel.curTime = [NSString stringWithFormat:@"%ld",(long)interval];
    
    
    [self getDataFromNetwork:self.chartParamsModel.chartList.firstObject];
   
    
}

#pragma mark ------ 前一天 -------
//日期累减
- (void)subTimeAction:(NSIndexPath *)indexpath{
    DevChartModel *chartModel = self.chartParamsModel.chartList[indexpath.section];
    
    if (chartModel.timeType == TimeType_Total) {
        return;
    }
    
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[chartModel.curTime integerValue]];
    NSDate *nextDate;
    if (chartModel.timeType == TimeType_Day) {
        nextDate = [date dateBySubtractingDays:1];
    }else if (chartModel.timeType == TimeType_Month){
        nextDate = [date dateBySubtractingMonths:1];
    }else if (chartModel.timeType == TimeType_Year){
        nextDate = [date dateBySubtractingYears:1];
    }
    NSTimeInterval interval = [nextDate timeIntervalSince1970];
    chartModel.curTime = [NSString stringWithFormat:@"%d",(int)interval];
    
    
    [self getDataFromNetwork:self.chartParamsModel.chartList.firstObject];
   
}



#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 1;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView *headView = kView;
    headView.backgroundColor = CFTabViewBgColor;
    UILabel *titleLab = [[QMUILabel alloc]init];
    titleLab.font = kBOLDSYSTEMFONT(16);
    titleLab.textColor = kColorRGB(0, 0, 0);
    titleLab.textAlignment = NSTextAlignmentLeft;
    titleLab.text = @"电池数据".rh_localized;
    [headView addSubview:titleLab];
    
    [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(headView).offset(15);
        make.bottom.mas_offset(-10);
     }];
    if(section ==0){
        titleLab.hidden = YES;
    };
   return nil;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if(section == 0)return 15;
    return 15;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.0;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    kWeakSelf;
    if(indexPath.section == 1){
        //能量统计
        RHDeviceLoadChartCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RHDeviceLoadChartCell"];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        cell.chartModel = self.chartParamsModel.chartList.firstObject;
        //选择参数
        cell.selectTopToolBlock = ^(NSInteger index) {
            [weakSelf selectTopTool:index atIndexpath:indexPath];
        };
        
        cell.subTimeBlock = ^{//日期往前
            [weakSelf subTimeAction:indexPath];
        };
        
        cell.addTimeBlock = ^{//日期往后
            [weakSelf addTimeAction:indexPath];
        };
        
        cell.changeTimeBlock = ^{//选择日期
            [weakSelf changeDate:indexPath];
        };
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }else{
        //底部电池数据
        RHDeviceLoadDataCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PEDeviceLoadCell"];
        cell.dic = self.batteryDataDic;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    
   
}


-(UIView *)listView
{
    return self.view;
}
@end
